package com.bkhc.product.repository;

import com.bkhc.product.entity.ProductPrice;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


@Repository
public interface ProductPriceRepository extends JpaRepository<ProductPrice,Integer>, JpaSpecificationExecutor<ProductPrice> {

    default Page<ProductPrice> findAll(ProductPrice productPrice, Pageable pageable){
        return findAll(new Specification<ProductPrice>() {
            @Override
            public Predicate toPredicate(Root<ProductPrice> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();

                if(!StringUtils.isEmpty(productPrice.getBrandCode())){
                    predicate.add(criteriaBuilder.equal(root.get("brandCode").as(String.class), productPrice.getBrandCode()));
                }
                if(!StringUtils.isEmpty(productPrice.getGoodsCode())){
                    predicate.add(criteriaBuilder.equal(root.get("goodsCode").as(String.class), productPrice.getGoodsCode()));
                }
                if(!StringUtils.isEmpty(productPrice.getPriceVersion())){
                    predicate.add(criteriaBuilder.equal(root.get("priceVersion").as(String.class), productPrice.getPriceVersion()));
                }
                Predicate[] pre = new Predicate[predicate.size()];
                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);

    }



    List<ProductPrice> findByBrandCodeAndGoodsCodeAndStatus(String brandCode, String productCode, String s);
}
